<template>
  <div class="hot-books-container"> <!-- 新增外层容器 -->
    <el-carousel 
      :interval="5000" 
      arrow="always"
      height="400px"
      trigger="hover">
  <el-carousel-item v-for="(book, index) in hotBooks" :key="index">
    <div class="carousel-content">
      <img :src="book.image">
      <div class="book-info">
        <h3>{{ book.title }}</h3>
        <p class="price">限时特价 ￥{{ book.price }}</p>
        <el-button type="danger" @click="addToCart(book)">立即抢购</el-button>
      </div>
    </div>
  </el-carousel-item>
</el-carousel>
  </div>
</template>

<style>
.hot-books-container {
  width: 1200px;
  margin: 20px auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.carousel-content {
  display: flex;
  padding: 20px;
  background: linear-gradient(to right, #f8f8f8 40%, #ffffff);
  height: 360px; /* 补充高度定义 */
}

.carousel-content img {
  width: 40%;
  height: 100%;
  object-fit: cover;
}
.book-info {
  padding: 40px;
  width: 60%;
}
</style>

<script>
export default {
  data() {
    return {
      hotBooks: [
        {
          id: 1,
          image: require('@/assets/img/jvm.jpg'),
          title: 'JVM核心技术',
          price: 79.9
        },
        {
          id: 2,
          image: require('@/assets/img/distributed.jpg'),
          title: '分布式系统实践',
          price: 89.9
        },
        {
          id: 3,
          image: require('@/assets/img/mysql.jpg'),
          title: 'MySQL内核解析',
          price: 99.9
        }
      ]
    }
  }, // 添加缺失的逗号
  methods: {
    addToCart(book) {
      // 删除以下登录验证代码块
      // const userId = sessionStorage.getItem('user_id');
      // if (!userId) {
      //  this.$message.warning('请先登录！');
      //  this.$router.push('/Login');
      //  return;
      // }

      const cartItems = JSON.parse(localStorage.getItem('cart') || '[]');
      
      const newItem = {
        id: book.id, // 补充缺失的id字段
        code: Date.now().toString(),
        bookimg: book.image,
        bookname: book.title,
        price: book.price,
        username: sessionStorage.getItem('user_name') || '游客', // 从session获取用户名
        createtime: new Date().toLocaleString(),
        difftime: 0,
        quantity: 1
      };

      // 添加重复商品检查
      const existing = cartItems.find(item => item.id === book.id);
      if (existing) {
        existing.quantity++;
      } else {
        cartItems.push(newItem);
      }

      localStorage.setItem('cart', JSON.stringify(cartItems));
      this.$message.success('商品已加入购物车！');
    }
  }
}
</script>
